<?php
declare (strict_types=1);

namespace app\command;

use app\webapi\controller\APiRedisServer;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;

class asyncShelvesTash extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('asyncshelvestash')
            ->setDescription('同步首页商品任务');
    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $output->writeln('同步首页商品任务');

        $data = Db::query("SELECT * FROM sy_goods_shelves WHERE state=1 ORDER BY id DESC", []);
        $cList = Db::query("SELECT * FROM sy_goods_category WHERE state=1 AND id>0 ORDER BY id DESC", []);
        $cList = array_column($cList,'id');
        // 删除原先的键
        $delKeys = APiRedisServer::selected(3)->keys("shelves_goods_*");
        if(count($delKeys) > 0){
            APiRedisServer::selected(3)->del($delKeys);
        }
        //全部分类列表中添加
        foreach ($data as $v){
            $map[ $v['id'] ] = json_encode($v,JSON_UNESCAPED_UNICODE);
            APiRedisServer::selected(3)->hmset("shelves_goods_0",$map);
        }
        //各个分类中添加
        if(!empty($cList) && count($cList) > 0){
            foreach ($cList as $cv){
                $fdata = array_filter($data,function($item) use ($cv){
                   return $item['id'] == $cv;
                });
                foreach ($fdata as $fv){
                    $map1[ $fv['id'] ] = json_encode($fv,JSON_UNESCAPED_UNICODE);
                    APiRedisServer::selected(3)->hmset("shelves_goods_".$cv,$map1);
                }
            }
        }
        // 清除计数器
        APiRedisServer::selected(3)->del("counter_shelves_goods");
        foreach ($data as $dv){
            $map2[ $dv['id'] ] = $dv['count'];
            APiRedisServer::selected(3)->hmset("counter_shelves_goods",$map2);
        }
        $output->writeln('商城首页商品更新:'.date('Y-m-d H:i:s',time()));


    }
}
